﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Carmall.Web.Models;

using Carmall.Entity;
using Carmall.BLL;

namespace Carmall.Web.Controllers
{
    [Authorize]
    public class UsersController : Controller
    {
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (Session["CurrentUser"] == null)
                requestContext.HttpContext.Response.Redirect("/Home");
        }
        #region 用户模块
        //
        // GET: /Users/
        // 用户首页
        public ActionResult Index()
        {
            List<UsersInfo> list = BLLFactory<Users>.Instance.GetAll();
            return View(list);
        }

        //
        // GET: /Users/Details/5
        // 显示详情
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Users/Create
        // 创建用户
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Users/Create
        // 创建用户
        [HttpPost]
        public ActionResult Create(FormCollection form)
        {
            try
            {
                // TODO: Add insert logic here
                var user = new UsersInfo();
                UpdateModel(user, new string[] { 
                    "Username",
                    "Password",
                    "Name",
                    "UserType",
                    "Tel",
                    "Address",
                    "Notes"
                }, form.ToValueProvider());
                /*
                TryUpdateModel(user, new string[] { 
                    "Username",
                    "Password",
                    "Name",
                    "UserType",
                    "Tel",
                    "Address",
                    "Notes"
                }, form.ToValueProvider());
                */
                if (String.IsNullOrEmpty(user.Username))
                    ModelState.AddModelError("Username", "请填写用户名");
                if (String.IsNullOrEmpty(user.Password))
                    ModelState.AddModelError("Password", "请填写密码");
                if(String.IsNullOrEmpty(user.Name))
                    ModelState.AddModelError("Name","请填写名称");

                if (ModelState.IsValid)
                {
                    UsersInfo u = BLLFactory<Users>.Instance.FindSingle("Username='" + user.Username + "'");
                    if (u == null)
                    {
                        int userId = BLLFactory<Users>.Instance.Insert2(user);
                        user.UserID = userId;
                    }
                    else
                    {
                        ModelState.AddModelError("Username", "该用户名已存在");
                        return View();
                    }
                    if (user.UserID > 0)
                    {
                        if (user.UserType == 2)
                            return RedirectToAction("Supplier", new { userId = user.UserID });
                        else if (user.UserType == 3)
                            return RedirectToAction("Purchaser", new { userId = user.UserID });
                        else
                            return RedirectToAction("Index");
                    }
                    return RedirectToAction("Index");
                }
                return View();
            }
            catch
            {
                return View();
            }
        }
        // 采购商
        public ActionResult Purchaser(int userId)
        {
            PurchasersInfo pur = BLLFactory<Purchasers>.Instance.FindSingle("UserID=" + userId);
            if(pur != null)
                ViewData.Model = pur;
            return View();
        }
        // 采购商
        [HttpPost]
        public ActionResult Purchaser(int userId,FormCollection form)
        {
            var isNew = false;
            var p = BLLFactory<Purchasers>.Instance.FindSingle("UserId=" + userId);
            if (p == null)
            {
                p = new PurchasersInfo();
                isNew = true;
            }
            TryUpdateModel(p, new string[] { 
                    "PurchaserNo",
                    "ShortName",
                    "Company",
                    "Mobile",
                    "Tel",
                    "Fax",
                    "Email",
                    "Contact",
                    "ZipCode",
                    "Place",
                    "Address",
                    "Notes",
                    "Licence",
                    "IDCard",
                    "Scope",
                    "Sales"
                }, form.ToValueProvider());
            p.UserID = userId;

            if (String.IsNullOrEmpty(p.PurchaserNo))
                ModelState.AddModelError("PurchaserNo", "请填写编号");
            if (String.IsNullOrEmpty(p.Company))
                ModelState.AddModelError("Company", "请填写公司名");
            if (ModelState.IsValid)
            {
                if (isNew)
                    BLLFactory<Purchasers>.Instance.InsertWithKey(p, null);
                else
                    BLLFactory<Purchasers>.Instance.Update(p, p.PurchaserNo);
                return RedirectToAction("Index");
            }
            return View();
        }
        // 供应商
        public ActionResult Supplier(int userId)
        {
            SuppliersInfo sup = BLLFactory<Suppliers>.Instance.FindSingle("UserID=" + userId);
            if(sup != null)
                ViewData.Model = sup;
            return View();
        }
        // 供应商
        [HttpPost]
        public ActionResult Supplier(int userId,FormCollection form)
        {
            var isNew = false;
            var s = BLLFactory<Suppliers>.Instance.FindSingle("UserId=" + userId);
            if (s == null) 
            { 
                s = new SuppliersInfo();
                isNew = true;
            }
            TryUpdateModel(s, new string[] { 
                    "SupplierNo",
                    "ShortName",
                    "CompanyName",
                    "Mobile",
                    "Tel",
                    "Fax",
                    "Email",
                    "Contact",
                    "ZipCode",
                    "Place",
                    "Address",
                    "Description",
                    "Notes",
                    "Licence",
                    "IdCard",
                    "Authorize",
                    "Cert"
                }, form.ToValueProvider());
            s.UserID = userId;

            if (String.IsNullOrEmpty(s.SupplierNo))
                ModelState.AddModelError("PurchaserNo", "请填写编号");
            if (String.IsNullOrEmpty(s.CompanyName))
                ModelState.AddModelError("CompanyName", "请填联系人名");
            if (ModelState.IsValid)
            {
                if (isNew)
                    BLLFactory<Suppliers>.Instance.InsertWithKey(s, null);
                else
                    BLLFactory<Suppliers>.Instance.Update(s, null);
                return RedirectToAction("Index");
            }
            return View();
        }
        //
        // GET: /Users/Edit/5
 
        public ActionResult Edit(int id)
        {
            var user = BLLFactory<Users>.Instance.FindByID(id.ToString());
            ViewData.Model = user;
            return View();
        }

        //
        // POST: /Users/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection form)
        {
            try
            {
                // TODO: Add insert logic here
                var user = BLLFactory<Users>.Instance.FindByID(id.ToString());
                TryUpdateModel(user, new string[] { 
                    "Username",
                    "Password",
                    "Name",
                    "UserType",
                    "Tel",
                    "Address",
                    "Notes"
                }, form.ToValueProvider());

                if (String.IsNullOrEmpty(user.Username))
                    ModelState.AddModelError("Username", "请填写用户名");
                if (String.IsNullOrEmpty(user.Password))
                    ModelState.AddModelError("Password", "请填写密码");
                if (String.IsNullOrEmpty(user.Name))
                    ModelState.AddModelError("Name", "请填写名称");

                if (ModelState.IsValid)
                {
                    if (user.UserID > 0)
                    {
                        BLLFactory<Users>.Instance.Update(user, user.UserID.ToString());
                    }
                    return RedirectToAction("Index");
                }
                return View();
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Users/Delete/5
 
        public ActionResult Delete(int id)
        {
            UsersInfo user = BLLFactory<Users>.Instance.FindByID(id.ToString());
            if (user != null)
            {
                if (user.UserType == 2)
                    BLLFactory<Suppliers>.Instance.DeleteByCondition("UserId=" + user.UserID);
                if (user.UserType == 3)
                    BLLFactory<Purchasers>.Instance.DeleteByCondition("UserId=" + user.UserID);
            }
            BLLFactory<Users>.Instance.Delete(id.ToString());
            return RedirectToAction("Index");
        }

        //
        // POST: /Users/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region Role 模块
        public ActionResult Roles()
        {
            List<RolesInfo> list = BLLFactory<Roles>.Instance.GetAll();
            return View(list);
        }

        public ActionResult AddRoles()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddRoles(FormCollection form)
        {
            var r = new RolesInfo();
            UpdateModel(r, new string[] { "RoleName" }, form.ToValueProvider());
            if (String.IsNullOrEmpty(r.RoleName))
                ModelState.AddModelError("", "请填写名称");

            r.RolePermission = form["roles"];
            if (ModelState.IsValid)
            {
                BLLFactory<Roles>.Instance.Insert(r);
                return RedirectToAction("Success","Home");
            }
            return View();
        }
        #endregion
    }
}
